/**
 * @page: 门店管理页面
 * @author:Elvis
 */

import { useState, useEffect, useMemo } from 'react';
import StoreList from './component/StoreList';
import FormRender from '@/components/FormRender';
import {
  queryStoreMangeList,
  queryRoleList,
  queryIsOpenOfflinePay,
  updateOfflinePaySwitch,
  updateFactoryList,
  autoPush,
  importExcel,
  updateDeductionSwitchOp,
  autoPushBatch,
  updateUnpickDisplay,
  updateDaiNaSwitch
} from './service.js';
import { stringify } from 'qs';
import { handleExportExcel } from '@/utils/utils.jsx';
import { message, notification } from 'antd';
import { useResize } from '@/hooks/useResize';
import { getFormItem } from './config.js';

const StoreManage = () => {
  const [data, setData] = useState([]); //列表数据
  const [query, setQuery] = useState({}); //查询条件
  const [roleList, setRoleList] = useState([]); //角色列表
  const [selectedRow, setSelectedRow] = useState([]); //批量操作
  const [selectedRowId, setSelectedRowId] = useState([]); //批量操作的id显示
  const [offlinePaymentShow, setOfflinePaymentShow] = useState(false); //是否展示线下支付字段
  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();
  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 10,
  });

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem();
  }, [])

  useEffect(() => {
    handleStoreList();
  }, [query, pages.current, pages.pageSize])

  useEffect(() => {
    handleRoleList();
    getIsOpenOfflinePay();
  }, []);

  const handleStoreList = async () => {
    setSelectedRow([]);
    setSelectedRowId([]);
    START_LOADING();
    const params = {
      ...query,
      current: pages.current,
      size: pages.pageSize,
    }
    if(params.storeIds?.length) {
      params.storeIds = params.storeIds?.join(',');
    } else {
      params.storeIds = undefined;
    }
    const { data, success } = await queryStoreMangeList(params);
    if (success) {
      //添加列表唯一标识
      let listKey = 0;
      const arr = data.records.map((item) => {
        listKey += 1;
        return Object.assign(item, { listKey });
      });
      setData(arr);
      setPages({
        ...pages,
        total: data.total
      });
    }
    END_LOADING();
  };

  const handleRoleList = async () => {
    const { data, success } = await queryRoleList();
    if (success) {
      setRoleList(data);
    }
  };

  const getIsOpenOfflinePay = async () => {
    const { data, success } = await queryIsOpenOfflinePay();
    if (success) {
      setOfflinePaymentShow(data);
    }
  };

  //线下支付开启关闭
  const handleStatusChange = async (e, record) => {
    START_LOADING();
    const { success, msg } = await updateOfflinePaySwitch({
      storeId: record.storeId,
      offlinePaySwitch: e ? 1 : 0,
    });
    END_LOADING();
    if (success) {
      message.success(msg);
      handleStoreList(query);
    }
  };

  const updateStraightFactorySwitch = async (storeId) => {
    START_LOADING();
    const { success } = await updateFactoryList({ storeId });
    if (success) {
      message.success('设置成功！');
      handleStoreList(query);
    }
    END_LOADING();
  };

  //允许自动推送订单打印
  const updateAutoPushSwitch = async (record, storeId) => {
    START_LOADING();
    const { success } = await autoPush({ storeId });
    if (success) {
      message.success('设置成功！');
      if (record.autoPush != '1') {
        updateDataSyncSwitch(record, false, 1)
      }
      handleStoreList(query);
    }
    END_LOADING();
  };

  //待拿货数据是否同步供应商
  const updateDataSyncSwitch = async (record, updateList = true, unpickDisplay) => {
    START_LOADING();
    const { success } = await updateUnpickDisplay({ storeId: record.storeId, unpickDisplay: unpickDisplay ? unpickDisplay : record.unpickDisplay == '1' ? 0 : 1 });
    if (success) {
      message.success('设置成功！');
      if (updateList) {
        handleStoreList(query);
      }
    }
    END_LOADING();
  }

  //是否开启代拿	
  const handlUpdateDaiNaSwitch = async (e, record) => {
    START_LOADING();
    const { success } = await updateDaiNaSwitch({
      storeId: record.storeId,
      daiNaSwitch: e ? 1 : 0,
    });
    if (success) {
      message.success('设置成功！');
      handleStoreList(query);
    }
    END_LOADING();
  };

  //退款抵扣开关
  const updateDeductionSwitch = async (storeId, deductionSwitch) => {
    let storeIds = storeId;
    if (!storeIds) {
      storeIds = selectedRow.map(item => item.storeId).join(',');
    }
    START_LOADING();
    const { success } = await updateDeductionSwitchOp({ storeIds, deductionSwitch });
    if (success) {
      message.success('设置成功！');
      handleStoreList(query);
    }
    END_LOADING();
  };


  //批量设置推送打印
  const batchSetPrintPush = async (isSwitch) => {
    return new Promise(async (resolve, reject) => {
      const storeIds = selectedRow.map(item => item.storeId).join(',');
      START_LOADING();
      const { success } = await autoPushBatch({ storeIds, buttonSwitch: isSwitch ? 1 : 0 });
      if (success) {
        message.success('设置成功！');
        handleStoreList(query);
      }
      END_LOADING();
      resolve(true)
    })
  };

  //导出列表
  const handleTableExport = () => {
    if (data.length) {
      START_LOADING();
      const nums = Math.ceil(pages.total / 10000);
      for (let i = 1; i <= nums; i++) {
        handleExportExcel(
          `/zjf-wms/store/exportExcel?${stringify({
            ...query,
            storeIds: query.storeIds?.length ? query.storeIds?.join(',') : undefined,
            current: i,
          })}`,
          '门店管理列表.xlsx',
          () => {
            END_LOADING();
          }
        );
      }
    } else {
      message.info('暂无可导出的数据');
    }
  };

  //导入修改
  const handleTableImport = async (info) => {
    console.log(info, 'info1')
    if (info.file.status === 'uploading') {
      START_LOADING();
      return;
    }
    if (info.file.status === 'done') {
      const { success, data } = await importExcel({
        file: info.file.originFileObj,
      });
      if (success) {
        notification.open({
          message: '导入结果',
          description: `成功修改${data}条数`,
          onClick: () => {
            console.log('Notification Clicked!');
          },
        });
        handleStoreList(query);
      }
      console.log(info, 'infofff')
      END_LOADING();
    } else if (info.file.status === 'error') {
      message.error('文件上传失败');
      END_LOADING();
    }
  };

  const pageProps = {
    pages,
    selectTotal: selectedRowId.length,
    handleChange(page, size) {
      pages.current = page;
      pages.pageSize = size;
      setPages(pages);
      handleStoreList(query, page, size);
    },
  };

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'supplier-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setPages({
        ...pages,
        current: 1
      });
      setQuery(val);
    },
    clickReset() {
      setPages({
        ...pages,
        current: 1
      });
      setQuery({});
    },
  }

  const storeListProps = {
    data,
    pages,
    roleList,
    selectedRow,
    selectedRowId,
    headerHeight,
    setPages,
    handleStoreList,
    offlinePaymentShow,
    updateStraightFactorySwitch,
    updateAutoPushSwitch,
    updateDataSyncSwitch,
    updateDeductionSwitch,
    handleTableExport,
    handleTableImport,
    batchSetPrintPush,
    total: pages.total,
    query,
    updateSelectRow: (data) => {
      setSelectedRow(data);
    },
    updateSelectedRowId: (data) => {
      setSelectedRowId(data);
    },
    clearSelect: () => {
      setSelectedRow([]);
      setSelectedRowId([]);
    },
    upDateSwitch(e, record) {
      handleStatusChange(e, record);
    },
    handlUpdateDaiNaSwitch(e, record) {
      handlUpdateDaiNaSwitch(e, record);
    },
  };

  return (
    <>
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <StoreList {...storeListProps} />
    </>
  );
};

export default StoreManage;